package info.itloser.learnkotlindemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import info.itloser.learnkotlindemo.R
import info.itloser.learnkotlindemo.bean.ChatMessage
import java.lang.NumberFormatException

/**
 * 说明：
 * 作者： itloser.info
 * 日期： 2022/3/30 17:17
 * 备注：
 */
class ChatMessageAdapter(private val messages: List<ChatMessage>) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    inner class LeftHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvMessage: TextView = itemView.findViewById(R.id.tv_message)
    }

    inner class RightHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvMessage: TextView = itemView.findViewById(R.id.tv_message)
    }

    override fun getItemViewType(position: Int): Int {
        return messages[position].type
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        when (viewType) {
            //收到的消息样式
            ChatMessage.TYPE_RECEIVED -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_chat_left, parent, false)
                return LeftHolder(view)

            }

            //发送的消息样式
            ChatMessage.TYPE_SEND -> {

                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_chat_right, parent, false)
                return RightHolder(view)

            }

            //非法样式
            else -> {
                throw IllegalArgumentException()
            }

        }

    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is LeftHolder -> {

                holder.tvMessage.text = messages[position].message

            }
            is RightHolder -> {

                holder.tvMessage.text = messages[position].message

            }

            //非法样式
            else -> {
                throw IllegalArgumentException()
            }

        }

    }

    override fun getItemCount(): Int {
        return messages.size
    }


}